// 观察者

class Observer {

    constructor(data) {
        this.observer(data);
    }

    observer(data) {
        if (!data || typeof data !== 'object') {
            return;
        }

        let keys = Object.keys(data);
        keys.forEach(key => {
            this.defineReactive(data, key, data[key]);
        })
    }

    defineReactive(obj, key, val) {
        let dep = new Dep();

        Object.defineProperty(obj, key, {
            enumerable: true,
            configurable: false,
            get() {
                Dep.target && dep.addSub(Dep.target);
                return val;
            },
            set(newValue) {
                val = newValue;

                dep.notify()
            },
        });
    }
}

//发布者
//功能： 1：管理订阅者， 2：通知

class Dep {
    constructor() {
        this.subs = [];
    }

    //添加订阅
    addSub(sub){
        this.subs.push(sub);
    }

    //集体通知
    notify(){
        this.subs.forEach(sub => {
            sub.update();
        })
    }


}